// API错误类定义
export class ApiClientError extends Error {
    public code?: string
    public status?: number
    public details?: Record<string, unknown>

    constructor(message: string, code?: string, details?: Record<string, unknown>) {
        super(message)
        this.name = 'ApiClientError'
        this.code = code
        this.details = details

        // Maintain proper prototype chain for instanceof checks
        Object.setPrototypeOf(this, ApiClientError.prototype)
    }
}

/**
 * Creates an ApiClientError from various input types
 */
export function createApiError(error: unknown, code?: string): ApiClientError {
    if (error instanceof Error) {
        return new ApiClientError(error.message, code, {
            originalError: error,
            originalStack: error.stack
        })
    }

    if (typeof error === 'string') {
        return new ApiClientError(error, code)
    }

    if (error && typeof error === 'object') {
        const message = 'message' in error ? (error as any).message : 'Unknown error'
        return new ApiClientError(
            message || 'Unknown error',
            code,
            error as Record<string, unknown>
        )
    }

    return new ApiClientError('Unknown error', code)
}

/**
 * Type guard to check if an error is an ApiClientError
 */
export function isApiError(error: unknown): error is ApiClientError {
    return error instanceof ApiClientError
}

export default ApiClientError